// 引入express
const express = require("express");
//创建express的实例
const app = express();
//域名配置
const port = 8002
const url = "http://127.0.0.1:"+port 
//跨域配置
app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

var fs = require("fs"); //引入fs，fs 是node中一个文件操作模块，包括文件创建，删除，查询，读取，写入。
let xlsxrd = require('node-xlsx');
var request = require('request');
var bodyParser = require('body-parser'); // 这个模块是获取post请求传过来的数据。
const path = require('path')
app.use(bodyParser.urlencoded({ extended: false })); // 判断请求体是不是json，不是的话把请求体转化为对象

var multer = require('multer'); //multer - node.js 中间件，用于处理 enctype="multipart/form-data
//app.use('/static', express.static('public'))// 静态资源地址
app.use(express.static('public')); // 设置静态图片访问的路径
app.use(multer({ dest: './public/' }).any())// 通过配置multer的dest属性， 将文件储存在项目下的tmp文件中
//workbook 对象，指的是整份 Excel 文档。我们在使用 js-xlsx 读取 Excel 文档之后就会获得 workbook 对象。

//大部分应用使用json格式,为了让express能够解析json格式的请求体,
//添加express.json中间件到app中,中间件自定义的比如log,扩展express功能
//请求前响应前做特定的
app.use(express.json());

//请求天气接口
const getWeatherinfo = (id) => {
  return new Promise((resolve, reject) => {
    request('http://www.weather.com.cn/data/sk/' + id + '.html', function (err, response, body) {
      //err 当前接口请求错误信息
      //response 一般使用statusCode来获取接口的http的执行状态
      //body 当前接口response返回的具体数据 返回的是一个jsonString类型的数据 
      //需要通过JSON.parse(body)来转换
      if (!err && response.statusCode == 200) {
        //todoJSON.parse(body)
        var res = JSON.parse(body);
        resolve(res.weatherinfo.temp);
      }
    });
  });
}

//获取所有天气
const getAllWeather = async (idArr) => {
  const retArr = [];

  // for...of loop to await without continuing the loop
  // but this will execute only sequentially
  for (let id of idArr) {
    console.log(id[0])
    let obj = {};
    obj.code = id[0];
    obj.province = id[1];
    const ret = await getWeatherinfo(id[0]);
    obj.temp = ret;
    retArr.push(obj);
  }

  // for parallel execution, use Promise.all()
  await Promise.all([...idArr.map(id => getWeatherinfo(id[0]))]);

  return retArr;
}


app.post('/fileUpload', async function (req, res) {// 上传接口
  let old = req.files[0].path //获取path: 'public\\upload\\0f625978d5d1a783b12e149718f8b634',
  let name = req.files[0].path + path.parse(req.files[0].originalname).ext
  fs.renameSync(old, './public/' + req.files[0].originalname)
  let excelFilePath = './public/' + req.files[0].originalname;
  console.log(name)
  // 读取excel中所有工作表的数据
  let list = xlsxrd.parse(excelFilePath);
  // 删除excel中第一个工作表的数据
  let data = list[0].data.splice(0, 1);
  var dats = list[0].data;
  let results = await getAllWeather(dats);
  res.json({
    'code': 1,
    'data': results,
    'msg': "成功"
  });

})

app.post('/fileDown', function (req, res) {// 下载接口
  let uploadList = req.body.data;
  console.log("收到请求体:", req.body.data)

  let datalist = [["地区编码", "地区名称", "气温"]];//设置excle首行标题
  for (let i = 0; i < uploadList.length; i++) {
    let arr = []
    let content = uploadList[i]
    for (let key in content) {
      console.log(content[key])
      arr.push(content[key])
    }
    console.log(arr)
    datalist.push(arr)
  }
  console.log(datalist);
  let list = [
    {
      name: "sheet",
      data: datalist,
    },
  ];
  console.log(list);
  //datalist.unshift(headers)

  const buffer = xlsxrd.build(list);
  fs.writeFile("./public/output.xlsx", buffer, function (err) {
    if (err) {
      res.json({
        'code': 1,
        'data': "",
        'msg': "生成失败"
      });
    } else {
      //return buffer
      res.json({
        'code': 0,
        'data': url+"/output.xlsx",
        'msg': "生成成功"
      });
    }
  });
})



app.listen(port, () => {
  console.log('express server listening at http://${url}:${port}');
});